package Protocols.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

import Protocols.ClientRequests.ClientRequest;
import Protocols.ClientRequests.Login;
import Protocols.ClientRequests.Logout;
import Protocols.ServerEvents.ServerEvent;

public class TestClient implements Runnable {
	
	Socket clientSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	Listener listener;
	boolean running =true;
	
	public TestClient(String host) throws ClassNotFoundException {
		try {
			//
			clientSocket = new Socket(host, 10000);
			out = new ObjectOutputStream(clientSocket.getOutputStream());
			in = new ObjectInputStream(clientSocket.getInputStream());
			listener=new Listener(this, in, out);
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
			
		}

	public void send(ClientRequest r) throws IOException {
		dump(r);
		Object o = (Object) r;
		out.writeObject(o);
		System.out.println(r.toString());
		if (r instanceof Logout) {shutdown();}
		running = false;
		}

	private void dump(ClientRequest r) throws IOException {
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = new ObjectOutputStream(bo);
		oo.writeObject(r);
		oo.flush();
		System.out.println(new String(bo.toByteArray()));
		
	}

	private void shutdown() {
		try {
			in.close();
			out.close();
			clientSocket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// TODO Auto-generated method stub
		
	}

	@Override
	public void run() {
		
		while (running) {
			Object o=null;
			System.out.println("Client: Sende Login");
			login();
			listener.start();
			System.out.println("Client: eingelogt");
			Scanner sc = new Scanner(System.in);
			sc.useDelimiter(System.getProperty("line.separator"));
			while (true){
				String s=sc.next();
				System.out.println("Eingegeben: "+s);
				if (s.equalsIgnoreCase("logout"))
					logout();
				try {
					out.writeObject(s);
				} catch (SocketException e){
					System.out.println("Client: Verbindung zum Server getrennt");
					System.exit(0);
				}catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		// TODO Auto-generated method stub
		
	}
	
	private void login() {
		try {
			send((ClientRequest) new Login());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void logout() {
		try {
			send(new Logout());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// TODO Auto-generated method stub
		
	}
		
	}

